const request=require("superagent");
const cheerio = require('cheerio');
const iconv = require('iconv-lite');
const util = require('util');
const charset = require("superagent-charset")(request);
const fs=require('fs');
var mysql      = require('mysql');
const assert = require('assert');
var connection = mysql.createConnection({
  host     : '127.0.0.1',
  user     : 'root',
  password : '123456',
  database : 'node'
});
connection.query = util.promisify(connection.query);


async function getList(){

	let sql=`select * from m_matter where area_id > 548 AND area_id < 570`;
	let result=await connection.query(sql);
	for (var i = 0; i < result.length; i++) {
		console.log(result[i]["id"],'')
		if(result[i]["ItemID"]){
			//事项
			let new_data = await connection.query(`select id from m_matter_a where ItemID = '${result[i]["ItemID"]}'`);
			if(new_data.length>0){
				console.error('事项数据已存在',result[i]["ItemID"])
				continue;
			}
			let datafloder = await connection.query(`select FolderCode from m_matter where id = '${result[i]["pid"]}'`);
			//查询目录id 
			let directory = await connection.query(`select id from m_matter_directory where area_id = '${result[i]["area_id"]}' and FolderCode = '${datafloder[0]["FolderCode"]}'`);
			if(directory.length==0){
				console.error('目录id为空')
				continue;
			}
			let addSql="INSERT INTO m_matter_a SET  ?";
			let addSqlParams = {
				'name':result[i]['name'],
				'directory_id':directory[0]['id'],
				'unit_id':result[i]['unit_id'],
				'service_type':result[i]['service_type'],
				'base_code':result[i]['base_code'],
				'implement_code':result[i]['implement_code'],
				'implement_subject':result[i]['implement_subject'],
				'implement_subject_code':result[i]['implement_subject_code'],
				'implement_subject_nature':result[i]['implement_subject_nature'],
				'exercise_level':result[i]['exercise_level'],
				'power_source':result[i]['power_source'],
				'joint_agency':result[i]['joint_agency'],
				'event_type':result[i]['event_type'],
				'limitation':result[i]['limitation'],
				'event_status':result[i]['event_status'],
				'event_version':result[i]['event_version'],
				'service_object':result[i]['service_object'],
				'processing_type':result[i]['processing_type'],
				'scope_application':result[i]['scope_application'],
				'intermediary_services':result[i]['intermediary_services'],
				'intermediary_services_name':result[i]['intermediary_services_name'],
				'application_form':result[i]['application_form'],
				'is_entry':result[i]['is_entry'],
				'is_online_office':result[i]['is_online_office'],
				'online_office_depth':result[i]['online_office_depth'],
				'computer_is_login':result[i]['computer_is_login'],
				'computer_link':result[i]['computer_link'],
				'phone_is_login':result[i]['phone_is_login'],
				'phone_link':result[i]['phone_link'],
				'is_self_service':result[i]['is_self_service'],
				'is_reservation':result[i]['is_reservation'],
				'is_charge':result[i]['is_charge'],
				'is_online_payment':result[i]['is_online_payment'],
				'is_express_delivery':result[i]['is_express_delivery'],
				'approval_result_type':result[i]['approval_result_type'],
				'approval_result_name':result[i]['approval_result_name'],
				'approval_result_sample':result[i]['approval_result_sample'],
				'ItemID':result[i]['ItemID'],
				'area_id':result[i]['area_id'],
				'collection_type':result[i]['collection_type'],
				'is_reduction':result[i]['is_reduction'],
			};
			await asySql(addSql,addSqlParams).then(insertId => {
				return insertId;
			}).catch(error => {
			  console.error(error); // 异步操作失败，输出错误信息
			});
		}else{
			//目录
			let new_data = await connection.query(`select id from m_matter_directory where area_id = '${result[i]["area_id"]}' and FolderCode = '${result[i]["FolderCode"]}'`);
			if(new_data.length>0){
				console.error('目录数据已存在',result[i]["FolderCode"])
				continue;
			}
			
			//下一层
			let m_matter_data = await connection.query(`select id,unit_id from m_matter where pid = '${result[i]["id"]}'`);
			let unit_id = m_matter_data[0]["unit_id"];
			if(m_matter_data[0]["unit_id"]==0){
				//下二层
				let m_matter_data_2 = await connection.query(`select unit_id from m_matter where pid = '${m_matter_data[0]["id"]}'`);
				if(m_matter_data_2.length == 0){
					console.error('下二层为空')
					continue;
				}
				unit_id = m_matter_data_2[0]['unit_id'];
			}

			if(unit_id<=0){
				console.error('unit_id为空')
				continue;
			}


			let level = 1;
			if(result[i]['pid']>0){
				let datafloder = await connection.query(`select FolderCode from m_matter where id = '${result[i]["pid"]}'`);
				let old_pid = await connection.query(`select id from m_matter_directory where area_id = '${result[i]["area_id"]}' and FolderCode = '${datafloder[0]["FolderCode"]}'`);
				if(old_pid.length==0){
					console.error('old_pid为空')
					return;
				}
				result[i]['pid'] = old_pid[0]['id'];
				let level = 2;
			}else{

			}
			

			let addSql="INSERT INTO m_matter_directory SET  ?";
			let addSqlParams = {
				'pid':result[i]['pid'],
				'area_id':result[i]['area_id'],
				'unit_id':unit_id,
				'name':result[i]['name'],
				'FolderCode':result[i]['FolderCode'],
				'level':level,
			};
			await asySql(addSql,addSqlParams).then(insertId => {
				return insertId;
			}).catch(error => {
			  console.error(error); // 异步操作失败，输出错误信息
			});
		}


	}



		
}

async function asySql(addSql,addSqlParams){
	return await new Promise(resolve => {
		connection.query(addSql,addSqlParams,function (err, result) {
	        if(err){
	         console.log('[INSERT ERROR] - ',err.message);
	         return;
	        }else{
	        	console.log('INSERT ID:',result.insertId);
		    	return resolve(result.insertId);
	        }        
	 		
		});
	})
		
}

getList();
